package com.metaverse.backend.service;

import com.metaverse.backend.config.RedisCacheKey;
import com.metaverse.backend.dto.CaptchaDTO;
import com.metaverse.backend.enums.CaptchaType;
import com.metaverse.backend.exception.BusinessException;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@AllArgsConstructor
public class CustomCaptchaService {

    private RedisTemplate<String, String> redisTemplate;

    /**
     * 验证码生成
     * @param captchaType
     * @return
     * @throws IOException
     * @throws FontFormatException
     */
    public CaptchaDTO gen(CaptchaType captchaType, int len) throws IOException, FontFormatException {
        String key = UUID.randomUUID().toString();
        int with = 90 * 2;
        int height = 32 * 2;
        if(len < 2){
            len = 2;
        }
        Captcha captcha = null;
        switch(captchaType){
            case SPEC:
                captcha = new SpecCaptcha(with, height, len);
                break;
            case CHINESE:
                captcha = new ChineseCaptcha(with, height, len);
                break;
            case CHINESE_GIF:
                captcha = new ChineseGifCaptcha(with, height, len);
                break;
            case ARITHMETIC:
                captcha = new ArithmeticCaptcha(with, height, len);
                break;
            default:
                throw new BusinessException("不支持的验证码类型：" + captchaType);

        }

        //captcha.setFont(com.wf.captcha.base.Captcha.FONT_8, 24 * 2);
        String code = captcha.text().toLowerCase();
        String image = captcha.toBase64();
        //缓存10分钟有效
        String cacheKey = RedisCacheKey.CAPTCHA_SERVICE + key;
        redisTemplate.opsForValue().set(cacheKey, code, 10, TimeUnit.MINUTES);
        return new CaptchaDTO(key, image);
    }


    public boolean verify(String key, String code, boolean clear) {
        boolean verify = false;
        String cacheKey = RedisCacheKey.CAPTCHA_SERVICE + key;
        String trueCode = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(trueCode) && trueCode.equalsIgnoreCase(code)) {
            verify = true;
        }

        //校验过就清除
        if(clear){
            redisTemplate.delete(cacheKey);
        }

        return verify;
    }


}
